#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include "Log.hpp"
#include "IntAddr.hpp"

const int defaultfd = -1;

using namespace MyLog;

using func_t = std::function<std::string(InetAddr &, const std::string &)>;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func)
        : _sockfd(defaultfd), _port(port), _func(func)
    {
    }

    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(Loglevel::FATAL) << "socket error " << errno;
            exit(1);
        }
        LOG(Loglevel::INFO) << "socket success: " << _sockfd;

        // 2. 绑定socket信息，ip和端口， ip(比较特殊，后续解释)
        // 2.1 填充sockaddr_in结构体
        struct sockaddr_in local;
        bzero(&local, sizeof local);
        local.sin_family = AF_INET;
        // 我会不会把我的IP地址和端口号发送给对方？
        // IP信息和端口信息，一定要发送到网络！
        // 本地格式->网络序列
        local.sin_port = htons(_port);
        // IP也是如此，1. IP转成4字节 2. 4字节转成网络序列 -> in_addr_t inet_addr(const char *cp);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(Loglevel::FATAL) << "bind error";
            exit(2);
        }
        else
        {
            LOG(Loglevel::INFO) << "bind success, sockfd: " << _sockfd;
        }
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            std::string ret;
            // 1.收消息
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
            if (s > 0)
            {
                InetAddr toclient(peer);
                buffer[s] = 0;

                // ret = _func(buffer);
                // LOG(Loglevel::DEBUG)<<"["<<peer_ip<<":"<<peer_port<<"]#"<<buffer;
                std::string ret = _func(toclient, buffer);
                LOG(Loglevel::INFO) << "回调func";

                // 2.发消息
                //  std::string echo_string = "server echo@ ";
                //  echo_string += ret;
                sendto(_sockfd, ret.c_str(), ret.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
    }

    ~UdpServer() {}

private:
    int _sockfd;
    // std::string _ip;
    uint16_t _port;
    bool _isrunning;
    func_t _func;
};
// AF_INET
// SOCK_DGRAM